package com.talkweb.baselibrary.utils;

import ohos.agp.components.Attr;
import ohos.agp.components.AttrSet;
import ohos.agp.components.element.Element;

import java.util.Optional;

public class AttrSetUtils {

    public static int getColor(AttrSet attrSet, String styleStr, int defaultValue) {
        Optional<Attr> attr = attrSet.getAttr(styleStr);
        if (attr.isPresent()) {
            int value = attrSet.getAttr(styleStr).get().getColorValue().getValue();
            return value;
        }

        return defaultValue;
    }

    public static int getDimension(AttrSet attrSet, String styleStr, int defaultValue) {
        Optional<Attr> attr = attrSet.getAttr(styleStr);
        if (attr.isPresent()) {
            int value = attrSet.getAttr(styleStr).get().getDimensionValue();
            return value;
        }

        return defaultValue;
    }

    public static String getString(AttrSet attrSet, String styleStr, String defaultValue) {
        Optional<Attr> attr = attrSet.getAttr(styleStr);
        if (attr.isPresent()) {
            String value = attrSet.getAttr(styleStr).get().getStringValue();
            return value;
        }

        return defaultValue;
    }

    public static int getInt(AttrSet attrSet, String styleStr, int defaultValue) {
        Optional<Attr> attr = attrSet.getAttr(styleStr);
        if (attr.isPresent()) {
            int value = attrSet.getAttr(styleStr).get().getIntegerValue();
            return value == -1 ? defaultValue : value;
        }

        return defaultValue;
    }

    public static Element getElement(AttrSet attrSet, String styleStr, Element defaultValue) {
        Optional<Attr> attr = attrSet.getAttr(styleStr);
        if (attr.isPresent()) {
            Element value = attrSet.getAttr(styleStr).get().getElement();
            return value;
        }

        return defaultValue;
    }

    /**
     * 获取图片资源
     * @param attrSet
     * @param styleStr
     * @param defaultValue
     * @return
     */
    public static int getImageResId(AttrSet attrSet, String styleStr, int defaultValue) {
        Optional<Attr> attr = attrSet.getAttr(styleStr);
        if (attr.isPresent()) {
            String value = attrSet.getAttr(styleStr).get().getStringValue();
            if (value.contains(":")) {
                String id=value.split(":")[1];
                return Integer.parseInt(id);
            }
        }

        return defaultValue;
    }

    public static boolean getBoolean(AttrSet attrSet, String styleStr, boolean defaultValue) {
        Optional<Attr> attr = attrSet.getAttr(styleStr);
        if (attr.isPresent()) {
            boolean value = attrSet.getAttr(styleStr).get().getBoolValue();
            return value;
        }

        return defaultValue;
    }

}
